import { AnyAction } from 'redux';
import { ActionType } from '../actions/list';

type State = {
    users: {
        ids: string[];
        entities: {
            [key: string]: {
                id: string;
                name: string;
                count: number;
            };
        };
    };
};

const initialState: State = {
    users: {
        ids: ['user1', 'user2', 'user3'],
        entities: {
            user1: { id: 'user1', name: 'user1', count: 0 },
            user2: { id: 'user2', name: 'user2', count: 0 },
            user3: { id: 'user3', name: 'user3', count: 0 },
        },
    },
};

export default (state = initialState, action: AnyAction) => {
    switch (action.type) {
        case ActionType.ADD_COUNT: {
            return {
                ...state,
                users: {
                    ...state.users,
                    entities: {
                        ...state.users.entities,
                        [action.id]: {
                            ...state.users.entities[action.id],
                            count: state.users.entities[action.id].count + 1,
                        },
                    },
                },
            };
        }
        case ActionType.DELETE: {
            const entities: any = { ...state.users.entities, [action.id]: null };
            delete entities[action.id];

            return {
                ...state,
                users: {
                    ...state.users,
                    ids: state.users.ids.filter((id) => id !== action.id),
                    entities,
                },
            };
        }
        default:
            return state;
    }
};
